
import { _decorator, Node, Component, Vec2, Graphics, Color, color } from 'cc';
import GeometryUtils from './GeometryUtils';
const {ccclass, property} = _decorator;

export default class PolygonDebugLine extends Component {
  	
    private _unusedGraphicses:Graphics [] = [];
    private _usedGraphics:{[key:number]:Graphics} = {};
    public DebugLine( id:number, points:Vec2[], strokeColor:Color = null):Graphics
    {
        let graph = this.CreateGraphics();
        graph.clear();
        this._usedGraphics[id] = graph;
        graph.strokeColor = strokeColor == null ? (GeometryUtils.IsClockwise(points) ? Color.RED : Color.GREEN) : strokeColor;
        for (let j = 0; j < points.length; j++) {
            if(j == 0)
            {
                graph.moveTo(points[j].x, points[j].y)
            }
            else
            {
                graph.lineTo(points[j].x, points[j].y)
            }
        }
        graph.lineTo(points[0].x, points[0].y)
        graph.stroke();
        return graph;
    }

    private CreateGraphics():Graphics
    {
        if(this._unusedGraphicses.length > 0)
        {
            let graphics = this._unusedGraphicses.pop();
            graphics.node.active = true;
            return graphics;
        }
        else
        {
            let debugNode = new Node("Graphics");
            debugNode.parent = this.node;
            let graphicsNode = debugNode.addComponent(Graphics);
            graphicsNode.lineWidth = 8;
            return graphicsNode;
        }
    }

    public RemoveDebugLine(id:number)
    {
        let graph = this._usedGraphics[id];
        if(graph)
        {
            delete this._usedGraphics[id];
            this._unusedGraphicses.push(graph);
            graph.node.active = false;
        }
    }
}

